package com.coocaa.ops.admin.v1.timedtask.job.impl;

import com.coocaa.ops.admin.v1.timedtask.biz.TimedTaskBizImpl;
import com.coocaa.ops.admin.v1.timedtask.job.AbstractQuartzJob;
import com.coocaa.ops.admin.v1.timedtask.model.BaseTimedInfo;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.biz.timedtask.entity.TimedTaskInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author bjh
 * @description
 * @date 2021/5/11 09:25
 */
@Service
public class CommonJobServiceImpl {
    @Autowired
    private TimedTaskBizImpl timedTaskBiz;
    @Autowired
    private MyQuartzJobServiceImpl myQuartzJobService;

    public void addJob(BaseTimedInfo model, Class<? extends AbstractQuartzJob> jobClazz) {
        TimedTaskInfoEntity timedTaskInfoEntityDb = timedTaskBiz.queryOneTimedTask(model.getTimedType(), model.getId(), model.getType());
        if (null != timedTaskInfoEntityDb) {
            //下线任务
            timedTaskBiz.updateStatus(timedTaskInfoEntityDb.getId(), ResourceStatusEnums.OFF_LINE.getStatus());
        }
        TimedTaskInfoEntity timedTaskInfoEntity = getTimedTaskInfoEntity(model);
        timedTaskBiz.add(timedTaskInfoEntity);
        //添加quartz定时
        //去除quartz定时
        myQuartzJobService.delJob(timedTaskInfoEntityDb);
        myQuartzJobService.addTimePointExecOnceQuartzJob(timedTaskInfoEntity, jobClazz);
    }

    public TimedTaskInfoEntity getTimedTaskInfoEntity(BaseTimedInfo model) {
        TimedTaskInfoEntity timedTaskInfoEntity = new TimedTaskInfoEntity();
        timedTaskInfoEntity.setResourceId(model.getId());
        timedTaskInfoEntity.setResourceType(model.getType());
        timedTaskInfoEntity.setTimedType(model.getTimedType());
        timedTaskInfoEntity.setReleaseTime(model.getReleaseTime());
        timedTaskInfoEntity.setCurrentOperator(model.getUserId());
        timedTaskInfoEntity.setStatus(ResourceStatusEnums.ON_LINE.getStatus());
        if (null != model.getVersion()) {
            timedTaskInfoEntity.setResourceVersion(model.getVersion());
        } else {
            timedTaskInfoEntity.setResourceVersion(timedTaskBiz.countTask(model.getTimedType(), model.getId(), model.getType()));
        }
        return timedTaskInfoEntity;
    }
}
